// utils/cos-upload.js
import { userAPI } from './api.js'

// 腾讯云COS SDK - 使用小程序兼容的方式
let COS
try {
  COS = require('cos-wx-sdk-v5')
} catch (error) {
  console.error('COS SDK加载失败:', error)
  // 如果SDK加载失败，提供一个降级方案
  COS = null
}

class COSUploader {
  constructor() {
    this.cos = null
    this.credentials = null
    this.bucket = null
    this.region = null
    this.expiredTime = 0
  }

  // 获取COS临时密钥
  async getCredentials() {
    try {
      const response = await userAPI.getCSToken()
      const { bucket, region, credentials, expiredTime } = response
      
      this.bucket = bucket
      this.region = region
      this.credentials = credentials
      this.expiredTime = expiredTime
      
      return response
    } catch (error) {
      console.error('获取COS临时密钥失败:', error)
      throw error
    }
  }

  // 检查密钥是否过期
  isCredentialsExpired() {
    return Date.now() >= this.expiredTime * 1000
  }

  // 初始化COS实例
  async initCOS() {
    if (!COS) {
      throw new Error('COS SDK未正确加载，请检查依赖安装')
    }
    
    // 如果没有密钥或密钥已过期，重新获取
    if (!this.credentials || this.isCredentialsExpired()) {
      await this.getCredentials()
    }

    this.cos = new COS({
      SecretId: this.credentials.tmpSecretId,
      SecretKey: this.credentials.tmpSecretKey,
      XCosSecurityToken: this.credentials.sessionToken,
      Protocol: 'https:'
    })
  }

  // 上传文件到COS
  async uploadFile(filePath, fileName = null) {
    try {
      await this.initCOS()

      // 如果没有指定文件名，生成一个
      if (!fileName) {
        const timestamp = Date.now()
        const random = Math.random().toString(36).substring(2, 15)
        const extension = filePath.split('.').pop()
        fileName = `avatar/${timestamp}_${random}.${extension}`
      }

      return new Promise((resolve, reject) => {
        // 显示上传进度
        wx.showLoading({
          title: '上传中...',
          mask: true
        })

        this.cos.postObject({
          Bucket: this.bucket,
          Region: this.region,
          Key: fileName,
          FilePath: filePath,
          onProgress: (progressData) => {
            console.log('上传进度:', progressData.percent)
            // 可以在这里更新进度显示
            if (progressData.percent >= 100) {
              wx.hideLoading()
            }
          }
        }, (err, data) => {
          wx.hideLoading()
          
          if (err) {
            console.error('COS上传失败:', err)
            reject(new Error(`上传失败: ${err.message || '未知错误'}`))
          } else {
            console.log('COS上传成功:', data)
            // 返回文件的完整URL
            const fileUrl = `https://${this.bucket}.cos.${this.region}.myqcloud.com/${fileName}`
            resolve({
              url: fileUrl,
              key: fileName,
              data: data
            })
          }
        })
      })
    } catch (error) {
      wx.hideLoading()
      console.error('上传文件失败:', error)
      throw error
    }
  }

  // 上传头像
  async uploadAvatar(filePath) {
    const timestamp = Date.now()
    const random = Math.random().toString(36).substring(2, 15)
    const extension = filePath.split('.').pop()
    const fileName = `avatar/${timestamp}_${random}.${extension}`
    
    return this.uploadFile(filePath, fileName)
  }
}

// 创建单例实例
const cosUploader = new COSUploader()

export default cosUploader 